/********************************************
* IECA, LAB 12                              *
* Test program for Interrupt driven UART    *
* driver.                                   *
*                                           *
* STK500 setup:                             *
* Header "RS232 spare" connected to RXD/TXD *
*   RXD = PORTD, bit0                       *
*   TXD = PORTD, bit1                       *
*                                           *
* Henning Hargaard 30/11 2011               *
*********************************************/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "HAL/uart.h"
#include "Application/protocol.h"
#include "Application/constants.h"
#include "Application/command.h"
#include "HAL/PWM.h"
#include "DisplayDriver/lcd162.h"
#include "TempDriver/TempI2CDriver.h"
#include <stdlib.h>
#define F_CPU 3686400
#include <avr/delay.h>
#include <string.h>
#include "HAL/ADC.h"

char receivedData[MAX_ARRAY];
int arrayIndex = 0;
char receiveMode = 1; 
char length = 0;


char* GetTemp()
{
	char temp[4];
	itoa(LM75_temperature(0), temp, 10);
	temp[3] = 0;
	static char returnval[10] = "Temp: "; 
	strcpy(&returnval[6], temp);
	
	return returnval;	
}

char* GetIR(int port)
{
	char ir1[4];
	itoa(readADC(port), ir1, 10);
	
	ir1[4] = 0;
	static char returnval[10] = "IR : ";
	returnval[2] = port + 48; 
	strcpy(&returnval[4], ir1);
	
	return returnval;	
}

ISR (USART_RXC_vect)
{
	if(receiveMode)
	{
		if(arrayIndex == 0)
		{
			receivedData[arrayIndex] = UDR;
		}
		else if(arrayIndex == 1)
		{
			receivedData[arrayIndex] = UDR;
			length = receivedData[arrayIndex];
			if (length > MAX_ARRAY)
			{
				SendData('A',"NACK");
				arrayIndex = 0 ;
				length = 0;
			}		
		}
		else if(length != 0)
		{
			length--;
			receivedData[arrayIndex] = UDR;
		}		
		else
		{
			receivedData[arrayIndex] = UDR;
			if(chcksum(receivedData,arrayIndex) == receivedData[arrayIndex])
			{
				packet2Command(receivedData, arrayIndex);
				length = 0;
				arrayIndex = 0;
				return;
			}				
			else
			{
				SendData('A',"NACK");
				length = 0;
				arrayIndex = 0;
				return;
			}
			
		}		
	}	  
	  arrayIndex++;
}

int main()
{
	initPWM();
	startRobot('F',3);
	
	InitADC();
	
	// Initialize USART (with RX interrupt enable)
	InitUART(19200, 8, 1);
  
	// Global interrupt enable
	sei();
	// Initialize LED port
	
	LCDInit();
	LCDClear();
	
	i2c_init();
	
  while (1)
  {
	
		LCDGotoXY(0,0);
		LCDDispString(GetIR(0));
		
		LCDGotoXY(0,1);
		LCDDispString(GetTemp());
		_delay_ms(1000);
	
  }
}

